# coding=utf-8
from 查找没用的图片 import listDir
from PIL import Image
import os
import re
    
def getImageInfo(imageUrl):
    img = os.path.basename(imageUrl)
    pattern1 = re.compile(r'(.+)@(\d*)x{0,1}\.png')
    pattern2 = re.compile(r'(.*)\.png')
    results = re.findall(pattern1, img)
    if len(results) > 0:
        scale = int(results[0][1])
        name = results[0][0]
    else:
        results = re.findall(pattern2, img)
        if len(results) > 0:
            scale = 3
            name = results[0]
    return name,scale,imageUrl

if __name__ == "__main__":
    basedir = "/Users/wsg/Desktop/3x"
    imageURLs = listDir(basedir, ["png"], reuslts=[])
    newDir = f"{basedir}/aa"
    type = 1#0是默认，创建@2x @3x，1是iOS模式，2是flutter模式
    if os.path.isdir(newDir) == False:
        os.mkdir(newDir)
    for x in [getImageInfo(imageUrl) for imageUrl in imageURLs]:
        newDir2 = f"{newDir}/{x[0]}.imageset"
        newDir3 = f"{newDir}/1x"
        newDir4 = f"{newDir}/2x"
        newDir5 = f"{newDir}/3x"
        if type == 1 and (os.path.isdir(newDir2) == False):
            os.mkdir(newDir2)
        if type == 2:
            if (os.path.isdir(newDir3) == False):
                os.mkdir(newDir3)
            if (os.path.isdir(newDir4) == False):
                os.mkdir(newDir4)
            if (os.path.isdir(newDir5) == False):
                os.mkdir(newDir5)
        for i in range(1,4):
            retainString = ""
            if i > 1 :
                retainString = f"@{i}x"
            image = Image.open(x[2])
            size = image.size[0] / x[1] * i,image.size[1] / x[1] * i
            
            newfileName = f"{newDir}/{x[0]}{retainString}.png"
            if type == 2:
                if i == 1:
                    newfileName = f"{newDir3}/{x[0]}.png"
                if i == 2:
                    newfileName = f"{newDir4}/{x[0]}.png"
                if i == 3:
                    newfileName = f"{newDir5}/{x[0]}.png"
            if type == 1:
                newfileName = f"{newDir2}/{x[0]}{retainString}.png"
                jsonFile = f"{newDir2}/Contents.json"
                filename1 = x[0]
                jsonContent = '''{
  "images" : [
    {
      "filename" : "filename1.png",
      "idiom" : "iphone",
      "scale" : "1x"
    },
    {
      "filename" : "filename1@2x.png",
      "idiom" : "iphone",
      "scale" : "2x"
    },
    {
      "filename" : "filename1@3x.png",
      "idiom" : "iphone",
      "scale" : "3x"
    }
  ],
  "info" : {
    "author" : "xcode",
    "version" : 1
  }
}
'''
                with open(jsonFile, 'w+',encoding='utf-8') as f:
                    f.write(jsonContent.replace("filename1", filename1))
                
            image.resize((max(int(size[0]),1),max(int(size[1]),1))).save(newfileName)
        print(f'{x[0]} saved')
